//
//  FQContactViewController.m
//  WeChat
//
//  Created by 方桥 on 16/5/17.
//  Copyright © 2016年 方桥. All rights reserved.
//

#import "FQContactViewController.h"
#import "FQChatViewController.h"
@interface FQContactViewController ()<NSFetchedResultsControllerDelegate>
{
    NSFetchedResultsController *_resultsContr;
}
/**好友数组*/
@property (nonatomic,strong) NSArray *users;

@end

@implementation FQContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //[self loadUsers1];
    [self loadUser2];
}
-(void)loadUser2
{
    NSManagedObjectContext *rosterContext = [FQXmppTool sharedFQXmppTool].rosterStorage.mainThreadManagedObjectContext;
    NSFetchRequest *requset = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //过滤
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"subscription != %@",@"none"];
    requset.predicate = pre;
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    requset.sortDescriptors = @[sort];
    //3.执行请求
    //3.1创建结果控制器
    // 数据库查询，如果数据很多，会放在子线程查询
    // 移动客户端的数据库里数据不会很多，所以很多数据库的查询操作都主线程
    _resultsContr = [[NSFetchedResultsController alloc]initWithFetchRequest:requset managedObjectContext:rosterContext sectionNameKeyPath:nil cacheName:nil];
    _resultsContr.delegate = self;
    //执行
    NSError *error = nil;
    [_resultsContr performFetch:&error];
    
}

#pragma mark -结果控制器的代理
#pragma mark -数据库内容改变
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
}

-(void)loadUsers1
{
    //1.上下文 关联XMPPRoster.sqlite文件
    NSManagedObjectContext *rosterContext = [FQXmppTool sharedFQXmppTool].rosterStorage.mainThreadManagedObjectContext;
    //2.Request 请求查询哪张表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    //设置排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors = @[sort];
    //3.执行请求
    NSError *error = nil;
    NSArray *users = [rosterContext executeFetchRequest:request error:&error];
    self.users = users;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //return self.users.count;
    return _resultsContr.fetchedObjects.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Id = @"contactCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:Id];
    }
    //获取对应的好友
    //XMPPUserCoreDataStorageObject *user = self.users[indexPath.row];
    XMPPUserCoreDataStorageObject *user = _resultsContr.fetchedObjects[indexPath.row];
    // 1.通过KVO来监听用户状态的改变
    //[user addObserver:self forKeyPath:@"sectionNum" options:NSKeyValueObservingOptionNew context:nil];
    
    switch ([user.sectionNum integerValue]) {//0.在线 1.离开 2.离线
        case 0:
            cell.detailTextLabel.text = @"在线";
            break;
        case 1:
            cell.detailTextLabel.text = @"离开";
            break;
        case 2:
            cell.detailTextLabel.text = @"离线";
            break;
        default:
            break;
    }
    
    cell.textLabel.text = user.displayName;
    //显示好友的头像
    if (user.photo) {//有头像
        cell.imageView.image = user.photo;
    }else{//从服务器获取头像
        NSData *imgeData = [[FQXmppTool sharedFQXmppTool].avatar photoDataForJID:user.jid];
        cell.imageView.image = [UIImage imageWithData:imgeData];
    }
    return cell;
}

//KVO方法
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
//{
//    [self.tableView reloadData];
//}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMPPUserCoreDataStorageObject *user = _resultsContr.fetchedObjects[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除好友
        [[FQXmppTool sharedFQXmppTool].roster removeUser:user.jid];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMPPJID *jid = [_resultsContr.fetchedObjects[indexPath.row] jid];
    //进入聊天控制器
    [self performSegueWithIdentifier:@"toChatVcSegue" sender:jid];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    id destVc = segue.destinationViewController;
    if ([destVc isKindOfClass:[FQChatViewController class]]) {
        FQChatViewController *chatVc = destVc;
        chatVc.friendJid = sender;
    }
}

@end
